<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/19
 * Time: 16:58
 */

namespace App\Http\Controllers\Manage;

use App\Http\Controllers\Manage\BaseController;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Http\Request;
use App\Repositories\Manage\RoleRepo;
use Illuminate\Support\Facades\DB;

class AdminController extends BaseController
{

    public function index(Request $request)
    {
        return view('manage.dashboard');

    }

    public function login()
    {
        return view('manage.login');

    }

    public function PostLogin(Request $request,roleRepo $roleRepo)
    {
        $username = $request->get('username');
        $password = $request->get('password');
        $captcha  = $request->get('captcha');

        $captcha=strtolower($captcha);
        if($captcha!=strtolower(session('captcha'))){
            return $this->ajaxResponse(1000, "验证码错误");
        }

        $user = DB::table('manage_user')
            ->where('name', $username)
            ->first();
        if(empty($user)) {
            return $this->ajaxResponse(1000, "用户不存在");
        }
        if($user->pass != md5($password)) {
            return $this->ajaxResponse(1000, "密码错误");
        }
        $roleId=$roleRepo->getRoleId('user_id = ?',[$user->uid]);
        if($roleId==null){
            return $this->ajaxResponse(1000, "你没有权限进入后台");
        }
        session(['manage_user'=> $user]);
        session()->forget('captcha');
        return $this->ajaxResponse(0, "登录成功");
    }


    public function loginOut()
    {
        session()->forget('manage_user');
        return view('manage.login');
    }


    public function getCaptcha()
    {
//        ob_get_clean();
//        $builder = new CaptchaBuilder;
//        $builder->build(120);//生成图像
//        $code = $builder->getPhrase();//获取验证码的内容
//        session(['captcha'=> $code]);
//        header('Content-type: image/jpeg');
//        $builder->output();

        //防止验证码在浏览器上出现乱码 使用laravel里面的response
        $builder = new CaptchaBuilder;
        $builder->build(120);//生成图像
        $code = $builder->getPhrase();//获取验证码的内容
        session(['captcha'=> $code]);
        $builder->output();
        return response('',200)->header('Content-type', 'image/jpeg');
    }


}